<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import VChart from 'vue-echarts'
import { getApiUrl, API_ENDPOINTS } from '../config/api'

interface MenuItem {
  id: number
  date: string
  mealType: string
  name: string
  nutrition: string
  specialDiet: string
  status: string
}

const menuItems = ref<MenuItem[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const showNutritionDialog = ref(false)
const isEdit = ref(false)
const currentId = ref<number | null>(null)

const nutritionChartOption = ref({
  title: {
    text: '营养成分分析',
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    formatter: '{b}: {c}g ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '20',
          fontWeight: 'bold'
        }
      },
      data: [
        { value: 15, name: '蛋白质', itemStyle: { color: '#91cc75' } },
        { value: 45, name: '碳水化合物', itemStyle: { color: '#fac858' } },
        { value: 12, name: '脂肪', itemStyle: { color: '#ee6666' } },
        { value: 5, name: '膳食纤维', itemStyle: { color: '#73c0de' } }
      ]
    }
  ]
})

// 添加图表DOM引用
const chartRef = ref(null)

const formData = ref({
  date: '',
  mealType: '',
  name: '',
  nutrition: '',
  specialDiet: [],
  status: '计划中'
})

const rules = {
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  mealType: [{ required: true, message: '请选择餐次', trigger: 'change' }],
  name: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
  nutrition: [{ required: true, message: '请输入营养信息', trigger: 'blur' }]
}

const formRef = ref(null)

// Fetch menu items from API
const fetchMenuItems = async () => {
  try {
    loading.value = true
    const response = await fetch(getApiUrl(API_ENDPOINTS.dining))
    if (!response.ok) throw new Error('获取数据失败')
    const data = await response.json()
    menuItems.value = Array.isArray(data) ? data.map(item => ({
      ...item,
      date: item.date.split('T')[0]
    })) : []
  } catch (error) {
    ElMessage.error('获取菜单列表失败')
    menuItems.value = []
  } finally {
    loading.value = false
  }
}

// Add new menu item
const addMenuItem = async () => {
  try {
    // 检查日期是否存在
    if (!formData.value.date) {
      ElMessage.error('请选择日期')
      return
    }

    // 确保日期格式正确
    let formattedDate = formData.value.date
    if (formData.value.date instanceof Date) {
      formattedDate = formData.value.date.toISOString().split('T')[0]
    } else if (typeof formData.value.date === 'string') {
      formattedDate = formData.value.date.split('T')[0]
    }

    const formattedData = {
      ...formData.value,
      date: formattedDate,
      specialDiet: formData.value.specialDiet.join(', ')
    }

    console.log('Submitting data:', formattedData) // 添加日志

    const response = await fetch(getApiUrl(API_ENDPOINTS.dining), {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formattedData)
    })

    if (!response.ok) {
      const errorData = await response.json()
      throw new Error(errorData.message || '添加失败')
    }
    
    ElMessage.success('添加菜品成功')
    dialogVisible.value = false
    await fetchMenuItems()
    resetForm()
  } catch (error) {
    console.error('添加菜品失败:', error)
    ElMessage.error(error.message || '添加菜品失败')
  }
}

// Edit menu item
const editMenuItem = async () => {
  if (!currentId.value) return
  
  try {
    // 检查日期是否存在
    if (!formData.value.date) {
      ElMessage.error('请选择日期')
      return
    }

    // 确保日期格式正确
    let formattedDate = formData.value.date
    if (formData.value.date instanceof Date) {
      formattedDate = formData.value.date.toISOString().split('T')[0]
    } else if (typeof formData.value.date === 'string') {
      formattedDate = formData.value.date.split('T')[0]
    }

    const formattedData = {
      ...formData.value,
      date: formattedDate,
      specialDiet: formData.value.specialDiet.join(', ')
    }

    console.log('Updating data:', formattedData) // 添加日志

    const response = await fetch(getApiUrl(`${API_ENDPOINTS.dining}/${currentId.value}`), {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formattedData)
    })

    if (!response.ok) {
      const errorData = await response.json()
      throw new Error(errorData.message || '更新失败')
    }
    
    ElMessage.success('更新菜品成功')
    dialogVisible.value = false
    await fetchMenuItems()
    resetForm()
  } catch (error) {
    console.error('更新菜品失败:', error)
    ElMessage.error(error.message || '更新菜品失败')
  }
}

// Handle edit button click
const handleEdit = (row: MenuItem) => {
  isEdit.value = true
  currentId.value = row.id
  formData.value = {
    ...row,
    date: row.date.split('T')[0],
    specialDiet: row.specialDiet ? row.specialDiet.split(', ') : []
  }
  dialogVisible.value = true
}

// Handle add button click
const handleAdd = () => {
  isEdit.value = false
  currentId.value = null
  resetForm()
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      await editMenuItem()
    } else {
      await addMenuItem()
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('请填写必填项')
  }
}

const resetForm = () => {
  formData.value = {
    date: '',
    mealType: '',
    name: '',
    nutrition: '',
    specialDiet: [],
    status: '计划中'
  }
}

onMounted(() => {
  fetchMenuItems()
})

// 修改营养数据的结构
const nutritionData = ref({
  totalCalories: 0,
  dailyStats: {
    calories: 0,
    protein: 0,
    carbs: 0,
    fat: 0,
    fiber: 0
  },
  recommendations: []
});

// 修改查看营养详情的处理函数
const handleViewNutrition = async (row) => {
  try {
    console.log('当前菜品数据:', row); // 添加日志
    if (!row || !row.nutrition) {
      ElMessage.warning('该菜品暂无营养信息');
      return;
    }

    // 直接从菜品数据中解析营养信息
    const nutrition = parseNutritionInfo(row.nutrition);
    console.log('解析后的营养数据:', nutrition); // 添加日志
    
    // 更新图表数据
    nutritionChartOption.value.series[0].data = [
      { value: nutrition.protein || 0, name: '蛋白质', itemStyle: { color: '#91cc75' } },
      { value: nutrition.carbs || 0, name: '碳水化合物', itemStyle: { color: '#fac858' } },
      { value: nutrition.fat || 0, name: '脂肪', itemStyle: { color: '#ee6666' } },
      { value: nutrition.fiber || 0, name: '膳食纤维', itemStyle: { color: '#73c0de' } }
    ];
    
    // 更新营养数据
    nutritionData.value = {
      totalCalories: nutrition.calories,
      dailyStats: {
        calories: nutrition.calories,
        protein: nutrition.protein,
        carbs: nutrition.carbs,
        fat: nutrition.fat,
        fiber: nutrition.fiber
      },
      recommendations: generateRecommendations(nutrition)
    };

    showNutritionDialog.value = true;
    
    // 等待DOM更新后初始化图表
    await nextTick();
    if (chartRef.value) {
      const chart = chartRef.value.chart;
      chart.resize();
    }
  } catch (error) {
    console.error('处理营养详情失败:', error);
    ElMessage.error('营养信息格式不正确，请检查输入格式');
  }
};

// 解析营养信息字符串
const parseNutritionInfo = (nutritionStr) => {
  if (!nutritionStr) {
    return {
      calories: 0,
      protein: 0,
      carbs: 0,
      fat: 0,
      fiber: 0
    };
  }

  try {
    // 匹配数字（支持多种格式）
    const calories = nutritionStr.match(/热量[：:\s]*(\d+)/) || 
                    nutritionStr.match(/(\d+)\s*卡路里/) || 
                    nutritionStr.match(/(\d+)\s*千卡/);
    const protein = nutritionStr.match(/蛋白质[：:\s]*(\d+)/) || 
                   nutritionStr.match(/蛋白质[：:\s]*(\d+)\s*g/);
    const carbs = nutritionStr.match(/碳水[化合物]*[：:\s]*(\d+)/) || 
                 nutritionStr.match(/碳水[化合物]*[：:\s]*(\d+)\s*g/);
    const fat = nutritionStr.match(/脂肪[：:\s]*(\d+)/) || 
                nutritionStr.match(/脂肪[：:\s]*(\d+)\s*g/);
    const fiber = nutritionStr.match(/[膳食]*纤维[：:\s]*(\d+)/) || 
                 nutritionStr.match(/[膳食]*纤维[：:\s]*(\d+)\s*g/);

    console.log('营养信息解析结果:', {
      原始数据: nutritionStr,
      热量: calories && calories[1],
      蛋白质: protein && protein[1],
      碳水: carbs && carbs[1],
      脂肪: fat && fat[1],
      纤维: fiber && fiber[1]
    });

    return {
      calories: calories ? parseInt(calories[1]) : 0,
      protein: protein ? parseInt(protein[1]) : 0,
      carbs: carbs ? parseInt(carbs[1]) : 0,
      fat: fat ? parseInt(fat[1]) : 0,
      fiber: fiber ? parseInt(fiber[1]) : 0
    };
  } catch (error) {
    console.error('解析营养信息失败:', error);
    return {
      calories: 0,
      protein: 0,
      carbs: 0,
      fat: 0,
      fiber: 0
    };
  }
};

// 生成营养建议
const generateRecommendations = (nutrition) => {
  const recommendations = [];
  
  if (nutrition.calories > 600) {
    recommendations.push('建议适当减���热量摄入');
  }
  if (nutrition.protein < 20) {
    recommendations.push('建议增加蛋白质的摄入');
  }
  if (nutrition.fiber < 10) {
    recommendations.push('建议增加膳食纤维的摄入');
  }
  if (nutrition.fat > 30) {
    recommendations.push('建议减少脂肪的摄入');
  }
  
  return recommendations.length > 0 ? recommendations : ['营养搭配合理，请继续保持'];
};

// 监听对话框显示状态
watch(showNutritionDialog, async (newVal) => {
  if (newVal) {
    await nextTick();
    if (chartRef.value) {
      const chart = chartRef.value.chart;
      chart.resize();
    }
  }
});

// 在模板中更新相关部分

</script>

<template>
  <div class="dining">
    <div class="header">
      <h2>餐饮管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">添加菜品</el-button>
        <el-button @click="showNutritionDialog = true">营养分析</el-button>
      </div>
    </div>

    <el-tabs type="border-card">
      <el-tab-pane label="每日菜单">
        <el-table 
          :data="menuItems" 
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="date" label="日期" width="120" />
          <el-table-column prop="mealType" label="餐次" width="100" />
          <el-table-column prop="name" label="菜品名称" />
          <el-table-column prop="nutrition" label="营养信息" show-overflow-tooltip />
          <el-table-column prop="specialDiet" label="特殊饮食">
            <template #default="{ row }">
              <el-tag
                v-for="diet in row.specialDiet?.split(', ')"
                :key="diet"
                size="small"
                class="mx-1"
              >
                {{ diet }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tag :type="row.status === '已发布' ? 'success' : row.status === '准备中' ? 'warning' : 'info'">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
              <el-button link type="primary" @click="handleViewNutrition(row)">
                营养详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      
      <el-tab-pane label="营养分析">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-card class="chart-card">
              <v-chart class="chart" :option="nutritionChartOption" autoresize ref="chartRef" />
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="analysis-card">
              <h3>营养评估报告</h3>
              <el-descriptions :column="1" border>
                <el-descriptions-item label="热量">2000 千卡/天</el-descriptions-item>
                <el-descriptions-item label="蛋白质">60-75g/天</el-descriptions-item>
                <el-descriptions-item label="碳水化合物">250-325g/天</el-descriptions-item>
                <el-descriptions-item label="脂肪">44-78g/天</el-descriptions-item>
                <el-descriptions-item label="膳食纤维">25-30g/天</el-descriptions-item>
              </el-descriptions>
              <div class="recommendations">
                <h4>建议</h4>
                <ul>
                  <li>增加全谷物的摄入，提供更多膳维</li>
                  <li>控制油脂使用量，选择健康脂肪</li>
                  <li>保证充足的蛋白质摄入，注意来源多样化</li>
                  <li>适当增加新鲜蔬果的供应</li>
                </ul>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <!-- Add/Edit Menu Item Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑菜品' : '添加菜品'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="formRef"
        :model="formData" 
        :rules="rules" 
        label-width="100px"
      >
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="formData.date"
            type="date"
            style="width: 100%"
            value-format="YYYY-MM-DD"
            :clearable="false"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="餐次" prop="mealType">
          <el-select v-model="formData.mealType" style="width: 100%">
            <el-option label="早餐" value="早餐" />
            <el-option label="午餐" value="午餐" />
            <el-option label="晚餐" value="晚餐" />
          </el-select>
        </el-form-item>
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="营养信息" prop="nutrition">
          <el-input
            v-model="formData.nutrition"
            type="textarea"
            :rows="3"
            :placeholder="'请按以下格式输入营养信息：\n热量450卡路里，蛋白质25g，碳水60g，脂肪15g，膳食纤维8g'"
          />
          <div class="nutrition-tips">
            <small>提示：请包含热量、蛋白质、碳水化合物、脂肪和膳食纤维的数值</small>
          </div>
        </el-form-item>
        <el-form-item label="特殊饮食">
          <el-select
            v-model="formData.specialDiet"
            multiple
            style="width: 100%"
          >
            <el-option label="低盐" value="低盐" />
            <el-option label="低脂" value="低脂" />
            <el-option label="无糖" value="无糖" />
            <el-option label="素食" value="素食" />
            <el-option label="软质" value="软质" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" style="width: 100%">
            <el-option label="计划中" value="计划中" />
            <el-option label="准备中" value="准备中" />
            <el-option label="已发布" value="已发布" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 营养分���对话框 -->
    <el-dialog
      v-model="showNutritionDialog"
      title="营养分析"
      width="800px"
      class="nutrition-dialog"
      :close-on-click-modal="false"
    >
      <el-row :gutter="24">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>营养成分分布</span>
              </div>
            </template>
            <v-chart class="chart" :option="nutritionChartOption" autoresize ref="chartRef" />
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="analysis-card">
            <template #header>
              <div class="card-header">
                <span>营养评估报告</span>
              </div>
            </template>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="总热量">{{ nutritionData.totalCalories }} 千卡</el-descriptions-item>
              <el-descriptions-item label="蛋白质">{{ nutritionData.dailyStats.protein }}g</el-descriptions-item>
              <el-descriptions-item label="碳水化合物">{{ nutritionData.dailyStats.carbs }}g</el-descriptions-item>
              <el-descriptions-item label="脂肪">{{ nutritionData.dailyStats.fat }}g</el-descriptions-item>
              <el-descriptions-item label="膳食纤维">{{ nutritionData.dailyStats.fiber }}g</el-descriptions-item>
            </el-descriptions>
            <div class="recommendations">
              <h4>营养建议</h4>
              <ul>
                <li v-for="(recommendation, index) in nutritionData.recommendations" :key="index">
                  {{ recommendation }}
                </li>
              </ul>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
  
</template>

<style scoped>
.dining {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-card,
.analysis-card {
  height: 400px;
  margin-bottom: 20px;
}

.chart {
  width: 100%;
  height: 100%;
  min-height: 300px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recommendations {
  margin-top: 20px;
}

.recommendations h4 {
  margin-bottom: 12px;
  color: #606266;
}

.recommendations ul {
  padding-left: 20px;
  margin: 0;
}

.recommendations li {
  margin-bottom: 8px;
  color: #606266;
  line-height: 1.5;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-descriptions__label) {
  width: 120px;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

.mx-1 {
  margin: 0 4px;
}

.nutrition-tips {
  margin-top: 4px;
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
}
</style>